<?php

require_once( 'core.php' );
require_once( 'current_user_api.php' );
require_once( 'string_api.php' );
require_once( 'file_api.php' );
require_once( 'bug_api.php' );
require_once( 'custom_field_api.php' );
require_once( 'collapse_api.php' );
require_once( 'relationship_api.php' );
require_once( 'project_api.php' );

auth_ensure_user_authenticated( );
//helper_begin_long_process( );

$t_plugin_path = config_get( 'plugin_path' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'HTTPclient.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'ReconciliationServices.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'TableMetadata.php' );
require_once( $t_plugin_path . 'DataRefine' . DIRECTORY_SEPARATOR . 'JSONstore.php' );


$refineURI = plugin_config_get( 'refineLocalURI' );
$refineHumanURI = plugin_config_get( 'refineBaseURI' ); //for human linking
if(!$refineURI){
	$refineURI = plugin_config_get( 'refineBaseURI' );
}



# extracts the user information for the currently logged in user
# and prefixes it with u_
$f_user_id = gpc_get_int( 'id', auth_get_current_user_id() );
$row = user_get_row( $f_user_id );

extract( $row, EXTR_PREFIX_ALL, 'u' );
$u_email = user_get_email( $u_id );
$u_realname = user_get_realname( $u_id );
$t_project_id = helper_get_current_project();


//check pending processes
	
	
	$RecServices = new ReconciliationServices;
	
	$RecServices->refineURI = $refineURI;
	$RecServices->refineHumanURI = $refineHumanURI;
	$RecServices->fallBack_issueProfile_id = gpc_get_int( 'profile_id', 0 ); // issue tracker profile ID.
	
	$RecServices->reconKey = $_POST["reconKey"];
	$RecServices->GRprojectID = $_POST["grProject"];
	$RecServices->baseColumnName = $_POST["baseColumnName"];
	
	
	$tableMetaObj = new TableMetadata;
	$tableMetaObj->refineURI = $refineURI;
	$tableMetaObj->currentUser = $f_user_id;
	$tableMetaObj->GRprojectID = $_POST["grProject"];
	$tableMetaObj->get_metadata();
	$tableMetadata = $tableMetaObj->currentMetadata;
	
	
	
	if($_POST["test"] == "test"){
		$message = array("testParams" => $_POST);
		$message["refineOK"] = true;
	}
	else{
	
		$message = $RecServices->CleanUpRawServiceData();
		if(is_array($message)){
			//post the message starting the reconcilation Google Refine server
			$HTTPclient = new HTTPclient;
			
			$HTTPclient->refineBaseURI = $refineURI;
			$HTTPclient->postActionURI = $RecServices->cleanupCommandURL;
			$HTTPclient->authorized = $authorized;
			$HTTPclient->message = $message; //json data as a string
			$HTTPclient->postData(); //send the post!
			
			
			if($HTTPclient->success != false){
				$message["refineOK"] = true;
				$message["postURI"]= $HTTPclient->postURI;
				$responseMessage = json_decode($HTTPclient->responseData, true);
				$message["refineRespose"] = $responseMessage;
				
				//now create an issue to notify / track about the results of the reconcilation	
				
				$tableMetadata = $RecServices->createReconcilationIssue($tableMetadata);
				$json = json_encode($tableMetadata, 1);
				$JSONstore = new JSONstore;
				$JSONstore->setDirectory("metadata");
				$JSONstore->save_json($projectID, $json);
				
				$message["newIssue"] = $RecServices->finalReconIssue;
				
				$RecServices->deleteReconProcess(); //delete parameters of ongoing process
				
			}
			else{
				$message["refineOK"] = false;
				$message["postURI"]= $HTTPclient->postURI;
				$message["error"] = $HTTPclient->errorMessage;
				$message["newIssue"] = false;
			}
		}
		else{
			if(is_array($RecServices->pendingProcesses)){
				$message["refineOK"] = false;
				$message["error"] = "Waiting for pending processes (".count($RecServices->pendingProcesses).")";
				$message["pending"] = $RecServices->pendingProcesses;
				$message["newIssue"] = false;
			}
		}
	}//en case of not a test

$output = json_encode($message, 1);

//now output for AJAX call from the Refine Login Screen
if(!isset($_GET["callback"])){
	header('Content-Type: application/json; charset=utf8');
	echo $output;
}
else{
	header('Content-Type: application/json; charset=utf8');
	$callback = $_GET["callback"];
	echo $callback."(".$output.");";
}


?>
